import { GeneralResponse, RequestSyncParamsType } from "@/apiTypes";
import { validateRequest } from "@/utils/utils";
import Taro, { getStorageSync } from "@tarojs/taro";
import { requestIsvTokenSync } from "@/libs/jd/runtime";
import { wechatLogin } from "@/libs/wechat/runtime/index";
/**
 * @author zzw
 * @date 2024-01-05 11:50:12
 * @desc 请求变量
 */
export const apiStore = new Proxy(
  {
    token: "Bearer " + Taro.getStorageSync("token") || "",
    openId: "",
    activityId: 0,
    clientid: Taro.getStorageSync("clientid") || "",
  },
  {
    get: (target, key) => {
      return target[key];
    },
    set: (target, key, value) => {
      target[key] = value;
      return true;
    },
  },
);

/**
 * @author zzw
 * @date 2023-11-22 11:22:48
 * @desc 请求地址
 */
const host = process.env.TARO_APP_API_URL;
/**
 * @author zzw
 * @date 2023-11-22 11:22:54
 * @desc 请求参数加密秘钥
 */
const appSecret = process.env.TARO_APP_SECRET_KEY;
/**
 * @author zzw
 * @date 2023-11-22 11:23:12
 * @desc 编译平台
 */
const env = process.env.TARO_ENV;
const apiUrl = {
  /**用户活动登录 */
  getToken: host + "/api/user/login",
  /**获取服务器时间 */
  getServiceTimestamp: host + "/api/activity/getServicTimestamp",
};

const getHeaders = (data: any) => {
  return {
    "Content-Type": "application/json",
    Authorization:
      "Bearer " + (process.env.TARO_ENV === "weapp" ? Taro.getStorageSync("token") : localStorage.getItem("token")) ||
      "",
    "X-GM-SIGNATURE": validateRequest(data, apiStore.openId, appSecret),
    clientid:
      (process.env.TARO_ENV === "weapp" ? Taro.getStorageSync("clientid") : localStorage.getItem("clientid")) || "",
  };
};

/**
 * @author zzw
 * @date 2023-11-22 11:20:20
 * @desc 需要鉴权的请求调用
 * @param {RequestSyncParamsType} obj 请求参数
 */
export const requestSync = (params: RequestSyncParamsType): Promise<GeneralResponse<any>> => {
  return new Promise((resolve, reject) => {
    try {
      Taro.request({
        url: params.url,
        method: params?.method || "POST",
        data: params?.data || {},
        header: getHeaders(params?.data || {}),
        success: function (res) {
          // console.log(`请求成功->${params.url}`, params, res.data);
          if (res.data.code == 200) {
            resolve(res.data);
          } else {
            // reject(res.data);
            if (res.data.code == 401 && res.data.msg == "认证失败，无法访问系统资源") {
              Taro.redirectTo({ url: "/pages/login/index" });
            } else {
              reject(Taro.showToast({ title: res.data.msg, icon: "none" }));
            }
          }
        },
        fail: function (error) {
          // console.log(`请求错误fail->${params.url}`, params, error);
          Taro.redirectTo({ url: "/pages/error/index" });
          reject(error);
          //  console.log(error,'error');
        },
      });
    } catch (error) {
      console.log(`请求错误->${params.url}`, params, error);
      Taro.redirectTo({ url: "/pages/error/index" });

      reject(error);
    }
  });
};

/**
 * @author zzw
 * @date 2023-11-21 18:27:41
 * @desc 获取token的方式，可以根据实际情况返回
 * @param
 */
export const getToken = async () => {
  let result = "";
  let code = "";
  switch (env) {
    case "jd":
      code = await getIsvToken(); //京东平台请求code的方式
      break;
    case "tt":
      code = await loginSync(); //抖音小程序平台请求code的方式
      break;
    case "weapp":
      code = await loginSync(); //微信小程序平台请求code的方式
      break;
    default:
      break;
  }

  const response = await requestSync({
    url: apiUrl.getToken,
    method: "POST",
    data: {
      activityId: apiStore.activityId,
      code: code,
    },
  });
  if (response.code === 200) {
    result = response.data;
    apiStore.token = result;
    if (process.env.NODE_ENV === "development") {
      Taro.setClipboardData({
        data: result,
      });
    }
  }
  return result;
};

/**
 * @author zzw
 * @date 2023-11-22 11:14:56
 * @desc 京东平台获取code的方式
 */
export const getIsvToken = async () => {
  const code = await requestIsvTokenSync({
    url: process.env.TARO_APP_JD_API_URL, //此处必须使用京东分配的域名才能调用成功
    id: "",
  });
  console.log("jdISVToken", code);
  return code;
};

export const loginSync = async (): Promise<string> => {
  return new Promise((resolve, reject) => {
    Taro.login({
      success: function (res) {
        resolve(res.code);
      },
      fail: function (res) {
        reject(res);
      },
    });
  });
};
